package solution.tree;

import common.TreeNode;
import common.util.TreeNodeUtil;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author : wenchao.long
 * @date : Created in 2021/06/29 16:14 周二
 * @description : 找树左下角的值
 */
public class FindBottomLeftValueSolution {

    public int findBottomLeftValue(TreeNode root) {
        int res = 0;
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            res = node.val;
            if (node.right != null) {
                queue.add(node.right);
            }
            if (node.left != null) {
                queue.add(node.left);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        TreeNode root = TreeNodeUtil.create(2, 1, 3);
        TreeNodeUtil.levelOrderList(root);

        int value = new FindBottomLeftValueSolution().findBottomLeftValue(root);
        System.out.println(value);

        int value1 = new FindBottomLeftValueSolution().findBottomLeftValue1(root);
        System.out.println(value1);
    }

    int maxK = -1;
    int val = 0;

    public int findBottomLeftValue1(TreeNode root) {
        dfs(root, 0);
        return val;
    }

    public void dfs(TreeNode node, int k) {
        if (node == null) {
            return;
        }
        if (k > maxK) {
            maxK = k;
            val = node.val;
        }
        dfs(node.left, k + 1);
        dfs(node.right, k + 1);
    }
}
